package com.aaa.service;

import com.aaa.dao.PermissionDao;
import com.aaa.dao.UserDao;
import com.aaa.entity.Permission;
import com.aaa.entity.Users;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/1 21:42
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MyUserService implements UserDetailsService {
    @Resource
    UserDao userDao;
    @Resource
    PermissionDao permissionDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<Users> users = userDao.queryByUsername(username);
        System.out.println(users.size());
        if (users != null && users.size()>0){
            List<Permission> permissions = permissionDao.queryByUserid(users.get(0).getUserid());
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            //用stream流把查到的权限 给 authorities
            authorities=permissions.stream().map(item->new
                    SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            User user = new User(username,users.get(0).getUserpwd() ,authorities );
            return user;
        }
        return null;
    }
}